package server

import (
	"context"
	"fmt"
	"github.com/spf13/cast"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"longmen/server/pkg/protobuf"
	pb "longmen/server/pkg/protobuf"
)

//admin 后台调用

// CleanChatHis 后台发起活动
func (s *TencentIM) CleanChatHis(ctx context.Context, req *pb.CleanChatHisReq) (*pb.ActivityResp, error) {
	err := db_main.DeleteEsChatHistoryByRoom(int(req.RoomId))
	if err != nil {
		return &pb.ActivityResp{Status: 0}, err
	}
	global.GetRds().Del(cache.GenChatHistoryRoom(int(req.RoomId)))

	// 清除统计
	var abid int
	err = global.GetR().Model(&models_main.ActivityBarrage{}).Where("status=1").Pluck("id", &abid).Error
	if err != nil {
		global.Log.Infof("Activity Error: %s", err.Error())
	}
	var liveID int64
	err = global.Live().Model(&models_live.Live{}).Where("anchorid=?", req.RoomId/100).Pluck("liveid", &liveID).Error
	if err != nil {
		global.Log.Infof("Activity Stat Error: %s", err.Error())
	}
	key := fmt.Sprintf("ACTIVITY_STAT_%d_%d_%d", req.RoomId, abid, liveID)
	global.GetRds().Del(key)

	return &pb.ActivityResp{Status: 1}, nil
}

// ActivityBarrage 后台发起活动
func (s *TencentIM) ActivityBarrage(ctx context.Context, req *pb.ActivityReq) (*pb.ActivityResp, error) {
	var ab models_main.ActivityBarrage
	err := global.GetR().Model(&models_main.ActivityBarrage{}).Where("status=1").First(&ab).Error
	if err != nil {
		global.Log.Infof("Activity Error: %s", err.Error())
	}

	if req.Status == 1 {
		// 创建聊天群组
		p := &protobuf.CreateGroupReq{AnchorId: int32(req.AnchorId) * 100, UserId: int32(req.AnchorId), GroupName: cast.ToString(int(req.AnchorId) + ab.ID)}
		s.CreteGroup(ctx, p)
	}

	// 清除活动相关的缓存，让 Activity 函数从数据库重新加载和缓存数据
	var liveID int64
	err = global.Live().Model(&models_live.Live{}).Where("anchorid=?", req.AnchorId).Pluck("liveid", &liveID).Error
	if err != nil {
		global.Log.Infof("Activity Stat Error: %s", err.Error())
	}
	cache.DelActivityCache(int(req.AnchorId), ab.ID, liveID)

	ab.RoomID = int(req.AnchorId * 100)
	ab.AnchorID = int(req.AnchorId)

	err = imsdk.GetSdk().BroadcastInterface(int(req.AnchorId), &models_main.ActivityBarrageBoard{
		Type:            "activity",
		Status:          req.Status,
		ActivityBarrage: ab,
	}, 0)
	if err != nil {
		return &pb.ActivityResp{Status: 0}, err
	}

	return &pb.ActivityResp{Status: 1}, nil
}
